from datetime import datetime

from itpay.utils import maestro_tracker
from .models import RechargeOrder, Complaint
from .const import *


def migrate_agency_recharge_success(cursor=None):
    """
    同步代理充值成功实践
    :return:
    """

    g = 0
    while True:
        orders = RechargeOrder.objects.filter(status=AgencyOrderStatusType.SUCCESS.value).order_by('id')
        if cursor:
            orders = orders.filter(id__gt=cursor)
        i = 0
        for o in orders[:500]:
            i += 1
            g += 1
            cursor = o.id
            try:
                success_time = o.success_at or o.updated_at
                maestro_tracker.track_maestro_agency_recharge_success(o.id, int(datetime.strftime(success_time, '%s')),
                                                                      o.agency_id, o.amount)
            except:
                print('migrate_agency_recharge_success: {}'.format(o.id))
            if i % 100 == 0:
                print('migrate_agency_recharge_success: ' + str(g))

        if i == 0:
            break


def migrate_agency_complain(cursor=None):
    """
    同步代理投诉
    :return:
    """

    g = 0
    while True:
        complains = Complaint.objects.filter().order_by('id')
        if cursor:
            complains = complains.filter(id__gt=cursor)
        i = 0
        for e in complains[:500]:
            i += 1
            g += 1
            cursor = e.id
            try:
                maestro_tracker.track_maestro_agency_complain(e.id, int(datetime.strftime(e.created_at, '%s')),
                                                              e.agency_id, e.mch_id, e.user_id,
                                                              e.complaint_types[0] if e.complaint_types else None)
            except:
                print('migrate_agency_complain: {}'.format(e.id))
            if i % 100 == 0:
                print('migrate_agency_complain: ' + str(g))

        if i == 0:
            break
